package com.xu.cloud.common.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;

/**
 * velocity-engine-core 模板渲染引擎工具类
 *
 * @author xuguan
 * @since 2024/1/26
 */
public class VelocityUtil {

    /**
     * 初始化Velocity模板渲染引擎
     */
    public static void initVelocity() {
        Properties prop = new Properties();
        // 设置velocity资源加载器
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        prop.put(Velocity.INPUT_ENCODING, StandardCharsets.UTF_8);
        Velocity.init(prop);
    }

    /**
     * 渲染模板
     *
     * @param templateName 模板名
     * @param context      渲染数据
     * @return 渲染完成后的字符串
     */
    public static String renderTemplate(String templateName, Map<String, Object> context) {
        final VelocityContext velocityContext = new VelocityContext(context);
        final Template template = Velocity.getTemplate(templateName, StandardCharsets.UTF_8.name());
        final StringWriter sw = new StringWriter();
        template.merge(velocityContext, sw);

        try {
            sw.close();
        } catch (IOException e) {
            // ignore IOException
        }

        return sw.toString();
    }
}
